#include "visualpositionselector.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QApplication>

VisualPositionSelector::VisualPositionSelector(QWidget *parent)
    : QWidget(parent)
    , m_buttonGroup(new QButtonGroup(this))
{
    setupUI();
}

void VisualPositionSelector::setupUI()
{
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(8);

    // 标题
    QLabel* titleLabel = new QLabel("页码位置", this);
    titleLabel->setStyleSheet("font-weight: bold; color: #333;");
    titleLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(titleLabel);

    // 九宫格布局容器
    QWidget* gridContainer = new QWidget(this);
    m_layout = new QGridLayout(gridContainer);
    m_layout->setContentsMargins(0, 0, 0, 0);
    m_layout->setSpacing(m_spacing);

    // 创建9个位置按钮
    QStringList positionNames = {
        "↖", "↑", "↗",
        "←", "●", "→",
        "↙", "↓", "↘"
    };

    for (int i = 0; i < 9; ++i) {
        QPushButton* button = new QPushButton(positionNames[i], this);
        button->setFixedSize(m_cellSize, m_cellSize);
        button->setCheckable(true);
        button->setProperty("position", i);

        // 设置按钮样式
        button->setStyleSheet(QString(
            "QPushButton {"
            "    border: 1px solid %1;"
            "    border-radius: 4px;"
            "    background-color: %2;"
            "    color: #555;"
            "    font-size: 14px;"
            "    font-weight: bold;"
            "}"
            "QPushButton:hover {"
            "    background-color: %3;"
            "}"
            "QPushButton:checked {"
            "    background-color: %4;"
            "    color: white;"
            "    border-color: %4;"
            "}"
        ).arg(m_borderColor.name())
         .arg(m_baseColor.name())
         .arg(m_hoverColor.name())
         .arg(m_selectedColor.name()));

        m_positionButtons.append(button);
        m_layout->addWidget(button, i / 3, i % 3);

        m_buttonGroup->addButton(button, i);
    }

    mainLayout->addWidget(gridContainer);

    // 描述标签
    QLabel* descLabel = new QLabel("点击选择页码位置", this);
    descLabel->setStyleSheet("color: #666; font-size: 11px;");
    descLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(descLabel);

    // 连接信号
    connect(m_buttonGroup, QOverload<QAbstractButton*>::of(&QButtonGroup::buttonClicked),
            this, [this](QAbstractButton* button) {
                int position = button->property("position").toInt();
                onButtonClicked(position);
            });

    // 设置默认选中底部居中
    setSelectedPosition(BottomCenter);
}

void VisualPositionSelector::setSelectedPosition(Position position)
{
    m_selectedPosition = position;
    updateButtonStates();

    // 更新描述文本
    if (parentWidget() && parentWidget()->findChild<QLabel*>("descLabel")) {
        QLabel* descLabel = parentWidget()->findChild<QLabel*>("descLabel");
        if (descLabel) {
            descLabel->setText(getPositionDescription(position));
        }
    }
}


void VisualPositionSelector::setCellSize(int size)
{
    m_cellSize = size;
    for (QPushButton* button : m_positionButtons) {
        button->setFixedSize(size, size);
    }
}

void VisualPositionSelector::setSpacing(int spacing)
{
    m_spacing = spacing;
    m_layout->setSpacing(spacing);
}

void VisualPositionSelector::setSelectedColor(const QColor& color)
{
    m_selectedColor = color;
    updateButtonStates();
}

void VisualPositionSelector::setHoverColor(const QColor& color)
{
    m_hoverColor = color;
    updateButtonStates();
}

void VisualPositionSelector::updateButtonStates()
{
    for (int i = 0; i < m_positionButtons.size(); ++i) {
        QPushButton* button = m_positionButtons[i];
        bool isSelected = (i == static_cast<int>(m_selectedPosition));
        bool isHovered = (i == static_cast<int>(m_hoveredPosition));

        QString bgColor = m_baseColor.name();
        QString textColor = "#555";
        QString borderColor = m_borderColor.name();

        if (isSelected) {
            bgColor = m_selectedColor.name();
            textColor = "white";
            borderColor = m_selectedColor.name();
        } else if (isHovered) {
            bgColor = m_hoverColor.name();
        }

        button->setStyleSheet(QString(
            "QPushButton {"
            "    border: 1px solid %1;"
            "    border-radius: 4px;"
            "    background-color: %2;"
            "    color: %3;"
            "    font-size: 14px;"
            "    font-weight: bold;"
            "}"
            "QPushButton:hover {"
            "    background-color: %4;"
            "}"
        ).arg(borderColor)
         .arg(bgColor)
         .arg(textColor)
         .arg(m_hoverColor.name()));

        button->setChecked(isSelected);
    }
}

QString VisualPositionSelector::getPositionName(Position position) const
{
    switch (position) {
        case TopLeft: return "左上";
        case TopCenter: return "顶部居中";
        case TopRight: return "右上";
        case MiddleLeft: return "左侧居中";
        case MiddleCenter: return "中心";
        case MiddleRight: return "右侧居中";
        case BottomLeft: return "左下";
        case BottomCenter: return "底部居中";
        case BottomRight: return "右下";
        default: return "未知";
    }
}

QString VisualPositionSelector::getPositionDescription(Position position) const
{
    return QString("当前位置：%1").arg(getPositionName(position));
}

void VisualPositionSelector::onButtonClicked(int position)
{
    Position pos = static_cast<Position>(position);
    if (pos != m_selectedPosition) {
        setSelectedPosition(pos);
        emit positionChanged(pos);
    }
    emit positionSelected(pos);
}

void VisualPositionSelector::paintEvent(QPaintEvent *event)
{
    QWidget::paintEvent(event);

    // 绘制额外的视觉效果
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制微妙的边框
    painter.setPen(QPen(m_borderColor, 1));
    painter.setBrush(Qt::NoBrush);
    painter.drawRoundedRect(rect().adjusted(0, 0, -1, -1), 4, 4);
}

void VisualPositionSelector::mousePressEvent(QMouseEvent *event)
{
    QWidget::mousePressEvent(event);
}

void VisualPositionSelector::mouseMoveEvent(QMouseEvent *event)
{
    // 计算悬停的位置
    QWidget* gridContainer = m_layout->parentWidget();
    if (gridContainer && gridContainer->geometry().contains(event->pos())) {
        QPoint localPos = event->pos() - gridContainer->geometry().topLeft();
        int col = localPos.x() / (m_cellSize + m_spacing);
        int row = localPos.y() / (m_cellSize + m_spacing);

        if (col >= 0 && col < 3 && row >= 0 && row < 3) {
            Position newHoverPos = static_cast<Position>(row * 3 + col);
            if (newHoverPos != m_hoveredPosition) {
                m_hoveredPosition = newHoverPos;
                updateButtonStates();

                // 显示工具提示
                QToolTip::showText(event->globalPosition().toPoint(),
                                  getPositionName(newHoverPos), this);
            }
        }
    }

    QWidget::mouseMoveEvent(event);
}

void VisualPositionSelector::leaveEvent(QEvent *event)
{
    m_hoveredPosition = m_selectedPosition;
    updateButtonStates();
    QToolTip::hideText();
    QWidget::leaveEvent(event);
}